import { _decorator, Component, EventTouch, input, Node, UITransform, v3, Vec2, Vec3, view, View } from 'cc';
import { Battle } from './Battle';
import { Player } from './Player/Player';
const { ccclass, property } = _decorator;

@ccclass('Joystick')
export class Joystick extends Component {
    @property(Node) frameNode: Node = null; // 摇杆背景
    @property(Node) handleNode: Node = null; // 摇杆手柄
    @property(Node) guideNode: Node = null; // 引导手节点
    @property(UITransform)
    Trans: UITransform = null;
    
    @property(Node)
    Center: Node = null;

    private _radius: number = 0;  // 摇杆的半径
    private _v2: Vec2 = new Vec2();  // 用于存储2D坐标
    private _touchWordPos: Vec3 = new Vec3();  // 触摸的世界坐标
    private _currPos: Vec3 = new Vec3();  // 当前触摸位置的节点坐标
    private readonly _startPos: Vec3 = new Vec3(0, 0);  // 摇杆初始位置
    private _listener: Function;  // 外部传入的事件回调函数
    private _target: any;  // 回调函数的上下文（通常是this）
    private _arrArg: any = [0];  // 回调函数的参数数组

    public onTouchMoveCallback:Function;
    public onTouchEndCallback:Function;

    public _direction:Vec3 = new Vec3();
    public get Direction() : Vec3 {
        return this._direction;
    }
    
    public SetCenter(worldPos:Vec3)
    {
        this.Trans.convertToNodeSpaceAR(worldPos, this._direction);
        if(Vec3.len(this._direction) > this._radius)
        {
            this._direction.normalize();
            // this.Center.setPosition(this._direction.normalize().multiplyScalar(this._radius));
        }
        else
        {
            // this.Center.setPosition(this._direction);
            this._direction.normalize();
        }
    }

    protected onEnable(): void {
        // 设置摇杆可触控区域为屏幕的一半
        this.node.getComponent(UITransform).height = view.getVisibleSize().height / 2;
        // 设置摇杆的半径
        this._radius = this.frameNode.getComponent(UITransform).contentSize.width / 2;

        // 注册触摸事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    protected onDestroy(): void {
        // 解除触摸事件
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    // 当触摸开始时调用
    onTouchStart(event: EventTouch) {
        // 获取触摸的世界坐标，并将其转换为节点的本地坐标
        const joyStickPos = event.getUILocation();
        this.node.getComponent(UITransform).convertToNodeSpaceAR(v3(joyStickPos.x, joyStickPos.y, 0), this._currPos);

        // 更新摇杆背景和手柄的位置
        this.frameNode.setPosition(this._currPos);
        this.handleNode.setPosition(this._currPos);
        this._startPos.set(this._currPos); // 更新摇杆初始位置
        this.guideNode.active = false;
        Battle.startGame = true;
    }

    // 当触摸移动时调用
    onTouchMove(event: EventTouch) {
        event.getUILocation(this._v2);
        this._touchWordPos.set(this._v2.x, this._v2.y, 0);
        // 将触摸的世界坐标转换为相对于frameNode的本地坐标
        this.node.getComponent(UITransform).convertToNodeSpaceAR(this._touchWordPos, this._currPos);

        // 计算手柄的距离和角度
        const distance = Vec3.distance(this._startPos, this._currPos);
        const radian = Math.atan2(this._currPos.y - this._startPos.y, this._currPos.x - this._startPos.x);

        // 判断手柄的位置是否超出摇杆的半径
        if (distance < this._radius) {
            this.handleNode.setPosition(this._currPos);
        } else {
            const x = this._startPos.x + Math.cos(radian) * this._radius;
            const y = this._startPos.y + Math.sin(radian) * this._radius;
            this.handleNode.setPosition(x, y);
        }

        // 摇杆的数据传递
        this._arrArg[0] = radian;
        this._arrArg[1] = true;
        this._listener && this._listener.apply(this._target, this._arrArg);
        if(this.onTouchMoveCallback)
        {
            this.onTouchMoveCallback(event);
        }

        // let playerController = Battle.playerNode.getComponent(Player);
        // playerController.isMoveing = true;
        // playerController.moveDirection = radian;
        // playerController.animController.UpdateAnim("walk2", true, 0);
    }

    // 当触摸结束时调用
    onTouchEnd(event: EventTouch) {
        // 重置手柄位置
        this.handleNode.setPosition(this._startPos);
        // 摇杆的数据传递
        this._arrArg[1] = false;
        this._listener && this._listener.apply(this._target, this._arrArg);
        if (Battle.playerNode && Battle.playerNode.getComponent(Player)) {
            Battle.playerNode.getComponent(Player).MoveToIdle();
        }
        if(this.onTouchEndCallback)
        {
            this.onTouchEndCallback(event);
        }
        // let playerController = Battle.playerNode.getComponent(Player);
        // playerController.isMoveing = false;
        // playerController.animController.UpdateAnim("stand2", true, 0);
    }

    // 注册摇杆事件回调
    onTouchEvent(listener: Function, target?: any) {
        this._listener = listener;
        this._target = target;
    }
}
